﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WcfClientGenerator.UI.Util
{
    public class WidthHeightHelperBehavior
    {
        #region Properties

        public static readonly DependencyProperty SetHeightToActualProperty =
            DependencyProperty.RegisterAttached("SetHeightToActual", typeof(bool), typeof(WidthHeightHelperBehavior),
            new FrameworkPropertyMetadata(
                (bool)false,
                new PropertyChangedCallback(OnSetHeightToActualChanged)));

        #endregion

        #region Methods (Public)
        
        public static bool GetSetHeightToActual(DependencyObject d)
        {
            return (bool)d.GetValue(SetHeightToActualProperty);
        }

        public static void SetSetHeightToActual(DependencyObject d, bool value)
        {
            d.SetValue(SetHeightToActualProperty, value);
        }
        
        #endregion

        #region Methods (Private)

        private static void OnSetHeightToActualChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                FrameworkElement element = d as FrameworkElement;
                RoutedEventHandler handler = null;
                handler = delegate
                {
                    element.Height = element.ActualHeight;
                    element.Loaded -= handler;
                };
                element.Loaded += handler;
            }
        }
        
        #endregion
    }
}
